const router = require('koa-router')()
const mongoose = require('mongoose')
const jwt = require('jsonwebtoken')
const config = require('../config')

const User = mongoose.model('User')

router.prefix('/users')

router.get('/', function (ctx, next) {
  ctx.body = 'this is a users response!'
})

router.get('/register', async function (ctx, next) {
  await ctx.render('register')
})

router.get('/login', async function (ctx, next) {
  await ctx.render('login')
})

router.get('/logout', async function (ctx, next) {
  ctx.cookies.set('authorization', '' , {maxAge: 0})
  ctx.response.redirect('/')
})

router.post('/register', async function (ctx, next) {
  await User.create(Object.assign({}, ctx.request.body))
  .then(doc => ctx.response.redirect('/users/login'))
  .catch(err => ctx.throw(500, err))
})

router.post('/login', async function (ctx, next) {

  await User.find({username:ctx.request.body.username,password:ctx.request.body.password})
  .then(user => {
    if(user.length !== 0) {
      let token = jwt.sign({ user : user[0] }, config.secretKey)
      ctx.cookies.set('authorization', token , {maxAge: 10 * 60 * 1000, path:'/',httpOnly: false})
      ctx.response.redirect('/')
    } else {
      ctx.body = { 'message' : '登录账号或密码错误' }
    }
  })
})

module.exports = router
